package cn.fl.project.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdPaySchTMQC;
import cn.fl.project.constant.PrjQuatPrpsConstant;
import cn.fl.project.dto.PrjPrdPaySchTMDTO;
import cn.fl.project.service.IPrjPrdPaySchTMApiService;
import cn.fl.project.service.IPrjPrdPaySchTMService;
import cn.fl.project.transform.PrjPrdPaySchMVOTransform;
import cn.fl.project.transform.PrjPrdPaySchTMVOTransform;
import cn.fl.project.vo.PrjPrdPaySchDVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.project.vo.PrjPrdPaySchTMVO;
import cn.fl.project.vo.PrjPrdPrpsFeeDetailVO;

/**
 * @Description: 项目产品支付表主信息表（挂靠公司版） 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class PrjPrdPaySchTMServiceImpl implements IPrjPrdPaySchTMService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IPrjPrdPaySchTMService.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IPrjPrdPaySchTMApiService prjPrdPaySchTMApiService;

	@Override
	public PrjPrdPaySchTMVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//TODO 业务逻辑
		PrjPrdPaySchTMDTO dto = null;//this.自定义ApiService.selectById(id);
		return PrjPrdPaySchTMVOTransform.toVO(dto);
	}

	@Override
	public Long add(PrjPrdPaySchTMVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//return this.prjPrdPaySchTMApiService.add(PrjPrdPaySchTMVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.prjPrdPaySchTMApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(PrjPrdPaySchTMVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.prjPrdPaySchTMApiService.modify(PrjPrdPaySchTMVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return false;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		//return this.prjPrdPaySchTMApiService.searchListPage(page);
		//TODO 业务逻辑
		return null;
	}

	@Override
	public PrjPrdPaySchMVO selectPrjPrdPaySchTMAndDetailById(Long id)
			throws BaseException {
		if(StringUtils.isEmpty(id)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"项目产品支付表id不能为空！");
		}
		PrjPrdPaySchMVO prjPrdPaySch = PrjPrdPaySchMVOTransform.toVO(this.prjPrdPaySchTMApiService.selectPrjPrdPaySchTMAndDetailById(id,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));
		getTotalValue(prjPrdPaySch);
		return prjPrdPaySch;
	}
	
	//计算首付款等信息 	
		private PrjPrdPaySchMVO getTotalValue(PrjPrdPaySchMVO vo) {
			List<PrjPrdPaySchDVO> detailList = vo.getPrjPrdPaySchDList();
			List<PrjPrdPrpsFeeDetailVO> prjPrdPayDetailList = new ArrayList<PrjPrdPrpsFeeDetailVO>();
			List<PrjPrdPaySchDVO> feeList = new ArrayList<PrjPrdPaySchDVO>();
			List<PrjPrdPaySchDVO> feeDetailList = vo.getFeeDetailList();
			//合计本金、合计利息、合计剩余本金、合计租金
			 double  totalRntAmt = 0d;//合计租金
			 double  totalPrinAmt = 0d;//合计本金
			 double  totalIntAmt = 0d;//合计利息
			 double totalRemPrinAmt = 0d;//合计剩余本金
			 double firstPayAmt = 0d;//首付款
			 Map<Integer,PrjPrdPrpsFeeDetailVO> prdPayMap = new HashMap<Integer,PrjPrdPrpsFeeDetailVO>();
			if(null!=vo){
				//计算首付款
				if(CollectionUtils.isNotEmpty(feeDetailList)){
					for (PrjPrdPaySchDVO fee : feeDetailList) {
						//首付款
						if(fee.getCntWayCd().equals(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CNT_WAY_DOWNPAY)){
							firstPayAmt = DecimalUtils.add(firstPayAmt, fee.getFeeAmt());
						}
						fee.setFeeAmt(DecimalUtils.convertFenToYuan(Double.valueOf((fee.getFeeAmt())).longValue()));
						feeList.add(fee);
					}
				}
				if(CollectionUtils.isNotEmpty(detailList)){
					for (PrjPrdPaySchDVO detail : detailList) {
							if(!prdPayMap.containsKey(detail.getPayPd())){
								PrjPrdPrpsFeeDetailVO feeDetail = new PrjPrdPrpsFeeDetailVO();
								feeDetail.setPayPd(detail.getPayPd());
								feeDetail.setIsModify(detail.getIsModify());
								feeDetail.setPayDt(detail.getPayDt());
								if(detail.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_RNT_PRICE)){
									//租金
									totalRntAmt = DecimalUtils.add(totalRntAmt, detail.getFeeAmt());
									feeDetail.setRntAmt(DecimalUtils.convertFenToYuan(Double.valueOf((detail.getFeeAmt())).longValue()));
								}
								if(detail.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_INT_PRICE)){
									//	利息			
									totalIntAmt = DecimalUtils.add(totalIntAmt, detail.getFeeAmt());
									feeDetail.setIntAmt(DecimalUtils.convertFenToYuan(Double.valueOf((detail.getFeeAmt())).longValue()));
								}
								if(detail.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_PRINT_PRICE)){
									//本金
									totalPrinAmt = DecimalUtils.add(totalPrinAmt, detail.getFeeAmt());
									feeDetail.setPrinAmt(DecimalUtils.convertFenToYuan(Double.valueOf((detail.getFeeAmt())).longValue()));
								}
								if(detail.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_REMPRIN_PRICE)){
									//剩余本金
									totalRemPrinAmt = DecimalUtils.add(totalRemPrinAmt, detail.getFeeAmt());
									feeDetail.setRemPrinAmt(DecimalUtils.convertFenToYuan(Double.valueOf((detail.getFeeAmt())).longValue()));
								}
								prdPayMap.put(detail.getPayPd(), feeDetail);
							}else{
								if(detail.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_RNT_PRICE)){
									//租金
									totalRntAmt = DecimalUtils.add(totalRntAmt, detail.getFeeAmt());
									prdPayMap.get(detail.getPayPd()).setRntAmt(DecimalUtils.convertFenToYuan(Double.valueOf((detail.getFeeAmt())).longValue()));
								}
								if(detail.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_INT_PRICE)){
									//	利息			
									totalIntAmt = DecimalUtils.add(totalIntAmt, detail.getFeeAmt());
									prdPayMap.get(detail.getPayPd()).setIntAmt(DecimalUtils.convertFenToYuan(Double.valueOf((detail.getFeeAmt())).longValue()));
								}
								if(detail.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_PRINT_PRICE)){
									//本金
									totalPrinAmt = DecimalUtils.add(totalPrinAmt, detail.getFeeAmt());
									prdPayMap.get(detail.getPayPd()).setPrinAmt(DecimalUtils.convertFenToYuan(Double.valueOf((detail.getFeeAmt())).longValue()));
								}
								if(detail.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_REMPRIN_PRICE)){
									//剩余本金
									totalRemPrinAmt = DecimalUtils.add(totalRemPrinAmt, detail.getFeeAmt());
									prdPayMap.get(detail.getPayPd()).setRemPrinAmt(DecimalUtils.convertFenToYuan(Double.valueOf((detail.getFeeAmt())).longValue()));
								}
							}
						
					}
				}
				 for (Integer key : prdPayMap.keySet()) {
					 	prjPrdPayDetailList.add(prdPayMap.get(key));
					  }
				
				 sortPrjPrdPayList(prjPrdPayDetailList);
				vo.setPrjPrdPayDetailList(prjPrdPayDetailList);
				vo.setFeeDetailList(feeList);
				vo.setActLsAmt(DecimalUtils.convertFenToYuan(Double.valueOf((vo.getActLsAmt())).longValue()));
				vo.setContAmt(DecimalUtils.convertFenToYuan(Double.valueOf((vo.getContAmt())).longValue()));
				vo.setEachEstRntAmt(DecimalUtils.convertFenToYuan(Double.valueOf((vo.getEachEstRntAmt())).longValue())); 
				vo.setTotLsItmAmt(DecimalUtils.convertFenToYuan(Double.valueOf((vo.getTotLsItmAmt())).longValue())); 
				vo.setTotalRntAmt(DecimalUtils.convertFenToYuan(Double.valueOf((totalRntAmt)).longValue()));
				vo.setTotalRemPrinAmt((DecimalUtils.convertFenToYuan(Double.valueOf((totalRemPrinAmt)).longValue()))); 
				vo.setTotalPrinAmt((DecimalUtils.convertFenToYuan(Double.valueOf((totalPrinAmt)).longValue()))); 
				vo.setTotalIntAmt((DecimalUtils.convertFenToYuan(Double.valueOf((totalIntAmt)).longValue()))); 
				vo.setTotalRemPrinAmt((DecimalUtils.convertFenToYuan(Double.valueOf((totalRemPrinAmt)).longValue()))); 
				vo.setFirstPayAmt(DecimalUtils.convertFenToYuan(Double.valueOf(firstPayAmt).longValue()));
				//结清数据分转元
				vo.setOverdueAmt(vo.getOverdueAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getOverdueAmt()).longValue()));
				vo.setPenaltyAmt(vo.getPenaltyAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getPenaltyAmt()).longValue()));
				vo.setActualAmt(vo.getActualAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getActualAmt()).longValue()));
				vo.setBeforeSettRntAmt(vo.getBeforeSettRntAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getBeforeSettRntAmt()).longValue()));
				vo.setDetAmt(vo.getDetAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getDetAmt()).longValue()));
				vo.setInsDep(vo.getInsDep()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getInsDep()).longValue()));
				vo.setFinalPayAmt(vo.getFinalPayAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getFinalPayAmt()).longValue()));
				vo.setLastRntAmt(vo.getLastRntAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getLastRntAmt()).longValue()));
				vo.setLastPrintAmt(vo.getLastPrintAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getLastPrintAmt()).longValue()));
				vo.setLastIntAmt(vo.getLastIntAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getLastIntAmt()).longValue()));
				vo.setOtherAmt(vo.getOtherAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getOtherAmt()).longValue()));
				vo.setPayAmount(vo.getPayAmount()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getPayAmount()).longValue()));
				//vo.setTotalFirstPayAmt(vo.getTotalFirstPayAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getTotalFirstPayAmt()).longValue()));
				vo.setRickDep(vo.getRickDep()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getRickDep()).longValue()));
				vo.setCheckPayAmt(vo.getCheckPayAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getCheckPayAmt()).longValue()));
				vo.setTotalActPrinAmt(vo.getTotalActPrinAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getTotalActPrinAmt()).longValue()));
				vo.setTotalActIntAmt(vo.getTotalActIntAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getTotalActIntAmt()).longValue()));
				vo.setTotalSettAmt(vo.getTotalSettAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getTotalSettAmt()).longValue()));
				vo.setBeforeSettLastIntAmt(vo.getBeforeSettLastIntAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getBeforeSettLastIntAmt()).longValue()));
				vo.setBeforeSettLastPrintAmt(vo.getBeforeSettLastPrintAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getBeforeSettLastPrintAmt()).longValue()));
				vo.setBreachAmt(vo.getBreachAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getBreachAmt()).longValue()));
				vo.setDiscountAmt(vo.getDiscountAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getDiscountAmt()).longValue()));
				vo.setFromSettLastRntAmt(vo.getFromSettLastRntAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getFromSettLastRntAmt()).longValue()));
				vo.setCurrentIntAmt(vo.getCurrentIntAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getCurrentIntAmt()).longValue()));
				vo.setTotalActRntAmt(vo.getTotalActRntAmt()==null?0:DecimalUtils.convertFenToYuan(Double.valueOf(vo.getTotalActRntAmt()).longValue()));
			}
			return vo;
		}
		
		private List<PrjPrdPrpsFeeDetailVO>sortPrjPrdPayList(List<PrjPrdPrpsFeeDetailVO> prjPrdPayList){
	        Collections.sort(prjPrdPayList, new Comparator<PrjPrdPrpsFeeDetailVO>(){  
	            public int compare(PrjPrdPrpsFeeDetailVO o1, PrjPrdPrpsFeeDetailVO o2) { 
	                if(o1.getPayPd().intValue() > o2.getPayPd().intValue()){  
	                    return 1;  
	                }  
	                if(o1.getPayPd().intValue() == o2.getPayPd().intValue()){  
	                    return 0;  
	                }  
	                return -1;  
	            }  
	      });  
	        return prjPrdPayList;
		}

		@Override
		public List<PrjPrdPaySchTMVO> searchList(PrjPrdPaySchTMQC qc)
				throws BaseException {
			return PrjPrdPaySchTMVOTransform.toVOList(this.prjPrdPaySchTMApiService.searchList(qc));
		}
}
